package com.jxs.security;



import com.jxs.security.resource.http.UriResource;

import java.util.HashSet;
import java.util.Set;

/**
 * @author jiangxingshang
 */
public class Session {

    private SessionManager sessionManager;

    private String token;
    private Data data;

    Session(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    Session(SessionManager sessionManager, String token, Data data) {
        this.sessionManager = sessionManager;
        this.token = token;
        this.data = data;
    }

    /**
     * 如果{@link #isLogin()}返回false，那么id会返回null。
     * @return
     */
    public String getId() {
        if(isLogin()) {
            return data.getId();
        } else {
            return null;
        }
    }

    public String getToken() {
        return token;
    }

    public Set<String> getResources() {
        return isLogin() ? data.getResources() : new HashSet<String>();
    }

    public boolean hasResource(UriResource res) {
        return getResources().contains(res.getId());
    }

    public void logout() {
        if(isLogin()) sessionManager.del(token);
    }

    public boolean isLogin() {
        return data != null;
    }
}
